Unique Word Abbreviation

An abbreviation of a word follows the form . Below are some examples of word abbreviations:

  1. a) it --> it (no abbreviation)
  2. 1
  3. b) d|o|g --> d1g
  4. 1 1 1
  5. 1---5----0----5--8
  6. c) i|nternationalizatio|n --> i18n
  7. 1
  8. 1---5----0
  9. d) l|ocalizatio|n --> l10n

Assume you have a dictionary and given a word, find whether its abbreviation is unique in the dictionary. A word’s abbreviation is unique if no other word from the dictionary has the same abbreviation.

Example:

  1. Given dictionary = [ "deer", "door", "cake", "card" ]
  2. isUnique("dear") -> false
  3. isUnique("cart") -> true
  4. isUnique("cane") -> false
  5. isUnique("make") -> true

Solution:

  1. public class ValidWordAbbr {
  2. Map<String, Set<String>> map = new HashMap<>();
  3. public ValidWordAbbr(String[] dictionary) {
  4. // build the hashmap
  5. // the key is the abbreviation
  6. // the value is a hash set of the words that have the same abbreviation
  7. for (int i = 0; i < dictionary.length; i++) {
  8. String a = abbr(dictionary[i]);
  9. Set<String> set = map.containsKey(a) ? map.get(a) : new HashSet<>();
  10. set.add(dictionary[i]);
  11. map.put(a, set);
  12. }
  13. }
  14. public boolean isUnique(String word) {
  15. String a = abbr(word);
  16. // it's unique when the abbreviation does not exist in the map or
  17. // it's the only word in the set
  18. return !map.containsKey(a) || (map.get(a).contains(word) && map.get(a).size() == 1);
  19. }
  20. String abbr(String s) {
  21. if (s.length() < 3)
  22. return s;
  23. return s.substring(0, 1) + String.valueOf(s.length() - 2) + s.substring(s.length() - 1);
  24. }
  25. }
  26. // Your ValidWordAbbr object will be instantiated and called as such:
  27. // ValidWordAbbr vwa = new ValidWordAbbr(dictionary);
  28. // vwa.isUnique("Word");
  29. // vwa.isUnique("anotherWord");